package com.zhang.family_doctor.service.impl;

import com.zhang.family_doctor.entity.R;
import com.zhang.family_doctor.entity.Treaty;
import com.zhang.family_doctor.mapper.TreatyMapper;
import com.zhang.family_doctor.service.TreatyService;
import com.zhang.family_doctor.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.UUID;

@Service
public class TreatyServiceImpl implements TreatyService {

    @Autowired
    private TreatyMapper treatyMapper;

    @Override
    public R saveOrUpdate(Treaty treaty, HttpServletRequest request) {

        String tokenBackstage = request.getHeader("tokenBackstage");
        String getName = TokenUtils.verifyAndGetName(tokenBackstage);

        int id = UUID.randomUUID().toString().replaceAll("-", "-").hashCode();
        id = id < 0 ? -id : id;

        Integer agreementType = treaty.getAgreementType();
        Treaty treatyByAgreementType = treatyMapper.getTreatyByAgreementType(agreementType);

        if (agreementType <= 3 && 0 < agreementType) {
            if (treatyByAgreementType != null) {

                treaty.setFounder(getName);
                treaty.setUpdateTime(new Date());
                treatyMapper.updateByAgreementType(treaty);
                return R.success("更新成功！");
            } else {

                treaty.setId(id);
                treaty.setCreateTime(new Date());
                treaty.setUpdateTime(new Date());
                treaty.setFounder(getName);
                treatyMapper.save(treaty);
                return R.success("插入成功！");
            }
        }else {
            return R.buildFailure("没有该类型的协议！");
        }
    }

    @Override
    public R getTreatyByAgreementType(Integer agreementType) {
        Treaty treatyByAgreementType = treatyMapper.getTreatyByAgreementType(agreementType);
        return R.success(treatyByAgreementType);
    }
}
